<template>
  <!-- VideoUpload.vue -->
  <div class="video-upload">
    <el-upload class="upload-demo" :multiple="false" :limit="1" :file-list="fileList"
      :headers="{ Authorization: token }" :action="requesturl()" :accept="acceptTypes" :on-exceed="handleExceed"
      :before-upload="beforeUpload" :on-success="handleSuccess" :on-error="handleError" :on-remove="handleRemove">
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">
        请上传{{ acceptTypes }}格式的视频，且不超过{{ maxSize }}MB
      </div>
    </el-upload>

    <!-- 预览 -->
    <div v-if="previewUrl" class="preview-wrapper">
      <video controls :src="previewUrl" class="preview-video"></video>
    </div>
  </div>
</template>

<script>
import { getToken } from '@/utils/token-util';
export default {
  name: 'VideoUpload',
  model: {
    prop: 'value',
    event: 'input'
  },
  props: {
    // 最大文件大小（MB）
    maxSize: {
      type: Number,
      default: 500
    },
    // 接受的文件类型
    acceptTypes: {
      type: String,
      default: '.mp4,.avi,.mov,.wmv,.flv,.mkv'
    },
    // 双向绑定的值
    value: {
      type: [Object, String],
      default: () => ({})
    }
  },
  data() {
    return {
      fileList: [],
      previewUrl: '',
      token: getToken(),
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        if (val && (val.url || typeof val === 'string')) {
          const url = typeof val === 'string' ? val : val.url
          this.fileList = [{
            name: val.name || url.split('/').pop(),
            url: url
          }]
          this.previewUrl = url
        } else {
          this.fileList = []
          this.previewUrl = ''
        }
      }
    }
  },
  methods: {
    // 文件超出个数限制时的钩子
    handleExceed(files, fileList) {
      this.$message.warning(`最多只能上传 1 个视频文件`)
    },

    // 上传前校验
    beforeUpload(file) {
      const isTypeValid = this.acceptTypes
        .split(',')
        .some(type => file.name.toLowerCase().endsWith(type.replace('.', '')))
      const isSizeValid = file.size / 1024 / 1024 < this.maxSize

      if (!isTypeValid) {
        this.$message.error(`只能上传 ${this.acceptTypes} 格式的视频!`)
        return false
      }

      if (!isSizeValid) {
        this.$message.error(`视频大小不能超过 ${this.maxSize}MB!`)
        return false
      }

      // 生成预览
      this.previewUrl = URL.createObjectURL(file)
      return true
    },

    // 上传成功回调
    handleSuccess(response, file) {
      const result = {
        name: file.name,
        url: response.url || URL.createObjectURL(file.raw),
        raw: file
      }
      this.$emit('input', response.data.url)
      // this.$emit('success', response, file)
      // this.$emit("on-change", res.data.url);
      this.$message.success('视频上传成功!')
    },

    // 移除文件回调
    handleRemove(file, fileList) {
      this.previewUrl = ''
      this.$emit('input', null)
      this.$emit('remove', file, fileList)
    },

    // handleError
    handleError(err, file) {
      console.error('上传失败:', err)
    },

    requesturl() {
      return process.env.VUE_APP_API_BASE_URL + "/file/upload";
      // return "http://agent.admin.creditcctv.cn/api/file/upload";
    },
  }
}
</script>

<style lang='scss' scoped>
.preview-wrapper {
  width: 178px;
  height: 178px;

  video {
    width: 100%;
    height: 100%;
  }
}
</style>
